import { ref } from 'vue'
import { useMapStore } from '@/stores/map.js'
import { useDialog } from '@/stores/dialogSwitch.js'
import { useDialogEvents } from '@/stores/dialogEvents.js'
import { storeToRefs } from 'pinia'
// 引入ol的交互式画笔
import { createDraw } from '@/Utils/createDraw.js'
// 引入拉框查询de中地接口
import { Query } from '@/Utils/Query.js'
// 引入多圈动画
import { setCanvas } from '@/Utils/setCanvas.js'

const { map } = storeToRefs(useMapStore())
const { dialogVisible } = storeToRefs(useDialog())
const { events } = storeToRefs(useDialogEvents())
// 定义画笔draw
let draw
// 定义多圈动画的点的位置坐标
let position = ref([])
// 定义多圈动画的图层数据源(在函数外面)
const high_source = new ol.source.Vector({})

export const queryEvents = () => {
  // 1. 创建画笔图层
  var source = new ol.source.Vector({})
  var layer = new ol.layer.Vector({
    source,
  })
  map.value.addLayer(layer)

  // 设置多圈动画的图层
  let canvas = setCanvas(map.value)
  const style = new ol.style.Style({
    image: new ol.style.Icon({
      img: canvas,
      imgSize: [canvas.width, canvas.height],
    }),
  })
  var high_layer = new ol.layer.Vector({
    source: high_source,
    title: '高亮图层',
    style,
  })
  map.value.addLayer(high_layer)

  /* 激活画笔 */
  draw = createDraw({
    type: 'Box',
    source,
  })
  // 2.添加画笔到地图
  map.value.addInteraction(draw)
  /* 激活完毕之后 */
  draw.once('drawend', function (evt) {
    /* 3. 拉框查询获取几何信息 */
    var geometry = evt.feature.getGeometry()
    var service = {
      name: 'guanggu',
      layerId: 2,
    }

    // 清除多圈动画数据源
    high_source.clear()
    /* 4. 根据几何信息调用中地接口,实现要素查询 */
    Query.queryByGeom({
      geometry,
      service,
      callback: (res) => {
        // 5. 清除交互式画笔和选中框
        // 清除画笔数据源--选中框
        // console.log(res)
        source.clear()
        // 清除交互式画笔
        // map.value.getInteractions(draw).pop()
        draw.setActive(false)

        // 6. 高亮选中的事件
        if (res) {
          events.value = res
          position.value = res
          // 7. 获取到选中事件的位置,设置多圈动画
          high_source.addFeatures(position.value)
          // 打开对话框
          dialogVisible.value = true
        }
      },
    })
  })
}
